package com.familyaccount.servlet;

import com.familyaccount.model.User;
import com.familyaccount.service.TransactionService;
import com.fasterxml.jackson.databind.ObjectMapper;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@WebServlet("/dashboard")
public class DashboardServlet extends HttpServlet {
    private TransactionService transactionService;
    private ObjectMapper objectMapper;

    @Override
    public void init() throws ServletException {
        transactionService = new TransactionService();
        objectMapper = new ObjectMapper();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect("index.jsp");
            return;
        }

        User user = (User) session.getAttribute("user");
        LocalDate now = LocalDate.now();
        int currentMonth = now.getMonthValue();
        int currentYear = now.getYear();

        try {
            // Get monthly summary
            BigDecimal monthlyIncome = transactionService.getMonthlyIncome(currentYear, currentMonth);
            BigDecimal monthlyExpense = transactionService.getMonthlyExpense(currentYear, currentMonth);
            BigDecimal monthlyBalance = monthlyIncome.subtract(monthlyExpense);

            // Get category statistics
            Map<String, BigDecimal> incomeByCategory = transactionService.getIncomeByCategory(currentYear, currentMonth);
            Map<String, BigDecimal> expenseByCategory = transactionService.getExpenseByCategory(currentYear, currentMonth);

            // Get monthly trend data (last 6 months)
            List<Map<String, Object>> monthlyTrend = transactionService.getMonthlyTrend(6);

            // Get daily income/expense for current month
            List<Map<String, Object>> dailyData = transactionService.getDailyIncomeExpense(currentYear, currentMonth);
            request.setAttribute("dailyLabels", objectMapper.writeValueAsString(
                dailyData.stream().map(m -> m.get("day")).toList()));
            request.setAttribute("dailyIncomeData", objectMapper.writeValueAsString(
                dailyData.stream().map(m -> m.get("income")).toList()));
            request.setAttribute("dailyExpenseData", objectMapper.writeValueAsString(
                dailyData.stream().map(m -> m.get("expense")).toList()));

            // Set attributes for JSP
            request.setAttribute("monthlyIncome", monthlyIncome);
            request.setAttribute("monthlyExpense", monthlyExpense);
            request.setAttribute("monthlyBalance", monthlyBalance);

            // Convert data for charts
            request.setAttribute("incomeCategories", objectMapper.writeValueAsString(incomeByCategory.keySet()));
            request.setAttribute("incomeData", objectMapper.writeValueAsString(incomeByCategory.values()));
            request.setAttribute("expenseCategories", objectMapper.writeValueAsString(expenseByCategory.keySet()));
            request.setAttribute("expenseData", objectMapper.writeValueAsString(expenseByCategory.values()));

            // Monthly trend data
            request.setAttribute("monthLabels", objectMapper.writeValueAsString(
                monthlyTrend.stream().map(m -> m.get("month")).toList()));
            request.setAttribute("monthlyIncomeData", objectMapper.writeValueAsString(
                monthlyTrend.stream().map(m -> m.get("income")).toList()));
            request.setAttribute("monthlyExpenseData", objectMapper.writeValueAsString(
                monthlyTrend.stream().map(m -> m.get("expense")).toList()));

            // 每个用户的总收支
            List<Map<String, Object>> userTotalList = transactionService.getTotalIncomeExpenseByUser();
            request.setAttribute("userTotalLabels", objectMapper.writeValueAsString(
                userTotalList.stream().map(m -> m.get("username")).toList()));
            request.setAttribute("userTotalIncomeData", objectMapper.writeValueAsString(
                userTotalList.stream().map(m -> m.get("income")).toList()));
            request.setAttribute("userTotalExpenseData", objectMapper.writeValueAsString(
                userTotalList.stream().map(m -> m.get("expense")).toList()));

            request.getRequestDispatcher("dashboard.jsp").forward(request, response);
        } catch (SQLException e) {
            request.setAttribute("error", "获取数据时发生错误，请稍后重试。");
            request.getRequestDispatcher("dashboard.jsp").forward(request, response);
        }
    }
} 